package com.mifengkong.frwidget.banner.customerbanner;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.mifengkong.frtools.util.FRDisplayMetrics;
import com.mifengkong.frwidget.R;


/**
 * Created by jiangyongxing on 2017/8/25.
 * 描述：
 */

public class BannerView extends RelativeLayout {

    private Context mContext;
    private RollViewPager mRollViewPager;
    private LinearLayout mDotContainer;//指示器的集合

    private BannerAdapter mBannerAdapter;//自定义的bannerAdapter

    //初始化点的指示器-点选中的drawable
    private Drawable mIndicaatorFousDrawable;
    private Drawable mIndicaatorNormalDrawable;

    //当前位置
    private int mCurrentPosition = 0;

    private int mDotGravity = -1;//点的位置默认左边
    private int mDotSize;//点的大小，也就是直径
    private int mDotDistance;//点之间的间距
    private int mDotMaginBottom;//点距离底部的距离
    private float mWidhtProportion;//宽高比，表示宽
    private float mHeightProportion;
    private NumberIndicatorView mNumberIndicatorView;
    private int mIndicatorType;
    private boolean mClickEnableWhenOneCount;
    private boolean mIndicatorShowWhenOneCount;
    private boolean isIndicatorRectangle;    //指示器是否是圆形
    private OnPageChangeListener listener;


    public BannerView(Context context) {
        this(context, null);
    }

    public BannerView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BannerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        //加载布局
        inflate(context, R.layout.layout_ui_banner, this);
        //初始化view
        intiView();

        initAttribute(attrs);

    }

    /**
     * 初始化自定义属性
     *
     * @param attrs
     */
    private void initAttribute(AttributeSet attrs) {
        TypedArray typedArray = mContext.obtainStyledAttributes(attrs, R.styleable.BannerView);
        mDotGravity = typedArray.getInt(R.styleable.BannerView_dotGravity, 0);
        mIndicaatorFousDrawable = typedArray.getDrawable(R.styleable.BannerView_dotIndicatorFocus);
        if (mIndicaatorFousDrawable == null) {
            mIndicaatorFousDrawable = new ColorDrawable(Color.RED);
        }
        mIndicaatorNormalDrawable = typedArray.getDrawable(R.styleable.BannerView_dotIndicatorNormal);
        if (mIndicaatorNormalDrawable == null) {
            mIndicaatorNormalDrawable = new ColorDrawable(Color.BLACK);
        }

        mDotSize = (int) typedArray.getDimension(R.styleable.BannerView_dotsize, dip2Px(8));
        mDotDistance = (int) typedArray.getDimension(R.styleable.BannerView_dotDistance, dip2Px(2.5f));
        mWidhtProportion = typedArray.getFloat(R.styleable.BannerView_heightProportion, 0);
        mHeightProportion = typedArray.getFloat(R.styleable.BannerView_widthProportion, 0);

        mIndicatorType = typedArray.getInt(R.styleable.BannerView_indicatorViewType, 0);
        mIndicatorShowWhenOneCount = typedArray.getBoolean(R.styleable.BannerView_indicatorShow_oneCount, false);
        mClickEnableWhenOneCount = typedArray.getBoolean(R.styleable.BannerView_clickEnable_oneCount, false);
        typedArray.recycle();
    }

    private void intiView() {
        mRollViewPager = (RollViewPager) findViewById(R.id.banner_vp);
        mDotContainer = (LinearLayout) findViewById(R.id.banner_dot);
    }

    public void setAdapter(BannerAdapter adapter) {
        mBannerAdapter = adapter;
        mRollViewPager.setScrollStatus(mBannerAdapter.getCount() > 1);
        mRollViewPager.setAdapter(adapter);
        mIndicatorType = (adapter.getCount() == 1) && !mIndicatorShowWhenOneCount ? 0 : mIndicatorType;
        initIndicatorView();
        //初始化广告的描述

        //bug修复
        mRollViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                //监听当前选中的位置
                pageSelected(position);
                if (listener != null) {
                    listener.onPageSelected(position);
                }
            }
        });

        dynamicAssignmentAspectRatio();

    }

    private void initIndicatorView() {
        if (mIndicatorType == 0) {
            mDotContainer.setVisibility(INVISIBLE);
        } else if (mIndicatorType == -1) {
            initDotIndicator();
        } else {
            initNumberIndicatorView();
        }
    }


    /**
     * 动态指定宽高比
     */
    private void dynamicAssignmentAspectRatio() {
        if (mHeightProportion == 0 || mWidhtProportion == 0) {
            return;
        }
        int width = getMeasuredWidth();

        getLayoutParams().height = (int) ((mHeightProportion * width) / mWidhtProportion);

    }

    /**
     * 页面切换时候的一个回调
     *
     * @param position
     */
    private void pageSelected(int position) {
        //把当前位置的indicator的选中点切换

        if (mIndicatorType == -1) {
            changeDotStatus(position);
        } else if (mIndicatorType == 1) {
            mNumberIndicatorView.setCurrentSelectPagePosition(position % mBannerAdapter.getCount() + 1);
        }

        //可以继续做一些其他的操作，比如有广告的描述的话，就可以在这里面设置
        mRollViewPager.setCurrentPosition(position % mBannerAdapter.getCount());
    }

    private void changeDotStatus(int position) {
        setDotNormal();
        mCurrentPosition = position % mBannerAdapter.getCount();
        DotIndicatorView currentIndicatorView = (DotIndicatorView) mDotContainer.getChildAt(mCurrentPosition);
        currentIndicatorView.setDrawable(mIndicaatorFousDrawable);
    }

    private void setDotNormal() {
        DotIndicatorView oldIndicatorView;
        for (int i = 0; i < mBannerAdapter.getCount(); i++) {
            oldIndicatorView = (DotIndicatorView) mDotContainer.getChildAt(i);
            oldIndicatorView.setDrawable(mIndicaatorNormalDrawable);
        }
    }

    /**
     * 初始化点的指示器
     */
    private void initDotIndicator() {

        int count = mBannerAdapter.getCount();

        mDotContainer.setGravity(getDotGravity());
        mDotContainer.removeAllViews();

        for (int i = 0; i < count; i++) {
            //不断的添加圆点
            DotIndicatorView indicatorView = new DotIndicatorView(getContext());
            LinearLayout.LayoutParams layoutParams;
            if (!isIndicatorRectangle) {
                layoutParams = new LinearLayout.LayoutParams(mDotSize, mDotSize);
            } else {
                layoutParams = new LinearLayout.LayoutParams(FRDisplayMetrics.dp2px(getContext(), 5), FRDisplayMetrics.dp2px(getContext(), 2));
            }
            layoutParams.leftMargin = layoutParams.rightMargin = mDotDistance;
            layoutParams.bottomMargin = mDotMaginBottom;
            indicatorView.setLayoutParams(layoutParams);
            indicatorView.setDrawable(i == 0 ? mIndicaatorFousDrawable : mIndicaatorNormalDrawable);
            mDotContainer.addView(indicatorView);
        }
    }

    private void initNumberIndicatorView() {
        int count = mBannerAdapter.getCount();
        mNumberIndicatorView = new NumberIndicatorView(getContext());
        LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        layoutParams.bottomMargin = dip2Px(15);
        layoutParams.rightMargin = dip2Px(25);
        mNumberIndicatorView.setLayoutParams(layoutParams);
        addView(mNumberIndicatorView);
        mNumberIndicatorView.setImageCount(count);
        mNumberIndicatorView.setCurrentSelectPagePosition(1);
    }

    private int getDotGravity() {
        switch (mDotGravity) {
            case -1:
                return Gravity.LEFT;
            case 0:
                return Gravity.CENTER;
            case 1:
                return Gravity.RIGHT;
        }
        return Gravity.CENTER;
    }

    private int dip2Px(float dip) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, getResources().getDisplayMetrics());
    }

    public void startRoll() {
        mRollViewPager.startRoll();
    }

    public void setBannerViewclipChildren(LayoutParams layoutParams, boolean clipChildren) {
        mRollViewPager.setLayoutParams(layoutParams);
        if (mBannerAdapter.getCount() == 1) {
            ((RelativeLayout) mRollViewPager.getParent()).setClipChildren(true);
        } else {
            ((RelativeLayout) mRollViewPager.getParent()).setClipChildren(clipChildren);
        }
    }

    public void setBannerViewclipChildren(int left, int top, int right, int bottom, boolean clipChildren) {
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        layoutParams.leftMargin = left;
        layoutParams.rightMargin = right;
        layoutParams.topMargin = top;
        layoutParams.bottomMargin = bottom;
        setBannerViewclipChildren(layoutParams, clipChildren);
    }

    public Drawable getmIndicaatorFousDrawable() {
        return mIndicaatorFousDrawable;
    }

    public void setmIndicaatorFousDrawable(Drawable mIndicaatorFousDrawable) {
        this.mIndicaatorFousDrawable = mIndicaatorFousDrawable;
    }

    public Drawable getmIndicaatorNormalDrawable() {
        return mIndicaatorNormalDrawable;
    }

    public void setmIndicaatorNormalDrawable(Drawable mIndicaatorNormalDrawable) {
        this.mIndicaatorNormalDrawable = mIndicaatorNormalDrawable;
    }

    public void setBannerViewclipChildren(boolean clipChildren) {
        setBannerViewclipChildren(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT), clipChildren);
    }

    public void setOnItemClickListener(onTouchClickListener listener) {
        mRollViewPager.setmListener(listener);
    }

    public void setCutdownTime(int millisecond) {
        mRollViewPager.setCurrentItem(millisecond);
    }

    //以下属性的设置需要在setAdapter方法之前，否者不起作用
    public void setCurrentPosition(int currentPosition) {
        mCurrentPosition = currentPosition;
    }

    /**
     * 设置点所在的位置，比如中   左   右
     *
     * @param dotGravity 中  0    左   -1  右 1
     */
    public void setDotGravity(int dotGravity) {
        mDotGravity = dotGravity;
    }

    /**
     * 设置点的直径，单位是DP，自定义View中自动转换
     *
     * @param dotSize
     */
    public void setDotSize(int dotSize) {
        mDotSize = dip2Px(dotSize);
    }

    public void setIndicatorRectangle(boolean isIndicatorRectangle) {
        this.isIndicatorRectangle = isIndicatorRectangle;
    }

    /**
     * 设置点与点之间的间距，单位是DP，自定义View中自动转换
     *
     * @param dotDistance
     */
    public void setDotDistance(float dotDistance) {
        mDotDistance = dip2Px(dotDistance);
    }

    /**
     * 设置宽高比中的宽的比例
     *
     * @param widhtProportion
     */
    public void setWidhtProportion(float widhtProportion) {
        mWidhtProportion = widhtProportion;
    }

    /**
     * * 设置宽高比中的高的比例
     *
     * @param heightProportion
     */
    public void setHeightProportion(float heightProportion) {
        mHeightProportion = heightProportion;
    }

    /**
     * 设置indicatorView的类型  有none  点  数字类型的   mIndicatorType  0  表示不显示  -1 表示dot    1  表示数字
     *
     * @param indicatorType
     */
    public void setIndicatorType(int indicatorType) {
        mIndicatorType = indicatorType;
    }

    public void setClickEnableWhenOneCount(boolean clickEnableWhenOneCount) {
        mClickEnableWhenOneCount = clickEnableWhenOneCount;
    }

    /**
     * 表示当只有一张图片的时候   是否还显示indicator
     *
     * @param indicatorShowWhenOneCount
     */
    public void setIndicatorShowWhenOneCount(boolean indicatorShowWhenOneCount) {
        mIndicatorShowWhenOneCount = indicatorShowWhenOneCount;
    }

    public void setDotMaginBottom(int dotMaginBottom) {
        mDotMaginBottom = dotMaginBottom;
    }

    public void setNumIndicatorViewBanckground(int color) {
        mNumberIndicatorView.setBackgroundColor(color);
    }

    public void setNumIndicatorViewBackground(Drawable drawable) {
        mNumberIndicatorView.setBackgroundDrawable(drawable);
    }

    public RollViewPager getRollViewPager() {
        return mRollViewPager;
    }

    public void setOnPageChangeListener(OnPageChangeListener listener) {
        this.listener = listener;
    }

    public interface OnPageChangeListener {
        void onPageSelected(int position);
    }
}